<template>
	<div>
		<!-- 上方搜索区域 -->
		<template v-if="pageInfo">
			<el-card v-if="isShowSearchCard" class="ipt-wrapper">
				<el-form
					:inline="true"
					class="flexRow"
					ref="searchFormRef"
					:model="queryParams"
					:style="[FilterFields.length === 0 ? 'display: flex;justify-content: flex-end;' : '']"
				>
					<el-form-item
						v-for="(SearchParamItem, idx) in FilterFields"
						:key="'searchParams' + idx"
						:label="SearchParamItem.Label || ''"
						class="flexCol iptCol"
					>
						<component
							:ref="(el: any) => setRefInfo(el, 'searchParams_input' + idx)"
							:pageInfo="pageInfo"
							:inputData="props.inputData"
							:pageData="pageData"
							:globalData="globalData"
							:is="getComponent(SearchParamItem.InputType)"
							:FieldItem="SearchParamItem"
							:filterIdx="idx"
							v-model="queryParams[SearchParamItem.FieldName]"
							located="Filter"
						>
						</component>
					</el-form-item>
					<template v-if="pageInfo.ButtonDefines?.length">
						<template v-for="(btn, index) in pageInfo.ButtonDefines" :key="index">
							<el-form-item
								v-if="props.isDisabledHanlde && btn.EventDefine?.DialogDefine.OpType === DialogType.query"
								class="btn"
								style="margin-bottom: 20px !important"
							>
								<el-button
									:type="transformBtnColor(btn.BtnStyleColor)"
									:[transformBtnType(btn.BtnStyleType)]="true"
									@click="handleBtnClick({ ...btn, type: 'Query', index })"
								>
									{{ btn.Title }}
								</el-button>
							</el-form-item>
							<el-form-item
								v-else-if="!props.isDisabledHanlde && handleShowBtn(btn, {}, FilterFields.length)"
								class="btn"
								style="margin-bottom: 20px !important"
							>
								<el-button
									:type="transformBtnColor(btn.BtnStyleColor)"
									:[transformBtnType(btn.BtnStyleType)]="true"
									@click="handleBtnClick({ ...btn, type: 'Query', index })"
								>
									{{ btn.Title }}
								</el-button>
							</el-form-item>
						</template>
					</template>
					<el-form-item v-if="props.isDisabledHanlde && !props.isTabRadio" class="btn" style="margin-bottom: 20px !important">
						<el-button type="success" plain @click="handleBatchGoParentTable">确定</el-button>
					</el-form-item>
					<el-form-item v-if="pageInfo.CheckBox" class="btn" style="margin-bottom: 20px !important">
						<el-button type="success" plain @click="handleBatchOperation">提交</el-button>
					</el-form-item>
					<el-form-item v-if="FilterFields.length" class="btn" style="margin-bottom: 20px !important">
						<el-button @click="handleReset">清空</el-button>
					</el-form-item>
				</el-form>
			</el-card>
			<!-- 分割线 -->
			<el-divider v-if="isShowSearchCard" />
			<!-- 表格数据展示区 -->
			<div class="table-box">
				<el-table
					:summary-method="getSummaries"
					:show-summary="pageInfo.NeedStatistics"
					:data="pageData.tableData"
					:header-cell-style="{ background: 'var(--next-table-head-bg-color)', color: 'var(--next-table-head-color)' }"
					:row-class-name="tableRowClassName"
					:cell-class-name="tableCellClassName"
					:highlight-current-row="props.isTabRadio || false"
					border
					:stripe="!(props.isTabRadio || false)"
					style="width: 100%"
					ref="tab"
					@cell-dblclick="handleCellDbClick"
					@selection-change="handleSelectTableChange"
					@current-change="handleCurrentTabItem"
				>
					<!-- 表格数据区 -->
					<!-- 索引,之前没有，暂时注释 TODO -->
					<!-- <el-table-column v-if="indexed" :index="indexMethod" type="index" align="center" width="auto" /> -->
					<!-- 复选 -->
					<el-table-column v-if="pageInfo.CheckBox || (props.isDisabledHanlde && !props.isTabRadio)" type="selection" align="center" width="60" />
					<template v-for="(field, index) in pageInfo.TableShowDefines" :key="'field-' + index">
						<!-- 字段渲染 -->
						<el-table-column
							v-if="field.FieldName && 'Col-' + field.FieldIndex"
							:prop="field.FieldName"
							:label="pageInfo.FieldDefines![field.FieldIndex!].Label"
							:width="pageInfo.FieldDefines![field.FieldIndex!].ColWidth ? pageInfo.FieldDefines![field.FieldIndex!].ColWidth :'auto'"
							:align="'center'"
						>
							<template #default="scope">
								<template v-if="pageInfo.FieldDefines![field.FieldIndex!].Extend.isTabFieldEdit">
									<component
										:ref="(el: any) => setRefInfo(el, 'table_cpn' + index)"
										:pageInfo="pageInfo"
										:inputData="props.inputData"
										:pageData="pageData"
										:globalData="globalData"
										:is="getComponent(pageInfo.FieldDefines![field.FieldIndex!].InputType)"
										:FieldItem="pageInfo.FieldDefines![field.FieldIndex!]"
										:filterIdx="index"
										:modelValue="getTabFieldValue(scope.row,pageInfo.FieldDefines![field.FieldIndex!])"
										@update:modelValue="($e:any) => scope.row[field.FieldName!] = $e"
										located="Table"
									>
									</component>
								</template>
								<!-- 将数据转换为图片 -->
								<template v-else>
									<template v-if="pageInfo.FieldDefines![field.FieldIndex!].InputType === 'el-img'">
										<template v-if="pageInfo.FieldDefines![field.FieldIndex!].InputDefine.fileType === '0' ">
											<el-image
												v-if="scope.row[field.FieldName]"
												style="width: 50px; height: 50px"
												:src="formatUrl(scope.row[field.FieldName], prefixUrl)[0]"
												fit="cover"
												:preview-src-list="formatUrl(scope.row[field.FieldName], prefixUrl)"
												:initial-index="0"
												preview-teleported
											/>
											<span v-else>暂无图片</span>
										</template>

										<span v-else-if="pageInfo.FieldDefines![field.FieldIndex!].InputDefine.fileType === '2'">
											{{ formatUrl(scope.row[field.FieldName], prefixUrl)[0] }}
										</span>
										<template v-else-if="pageInfo.FieldDefines![field.FieldIndex!].InputDefine.fileType === '1'">
											<el-button
												v-for="url in formatUrl(scope.row[field.FieldName], prefixUrl)"
												:key="url"
												type="primary"
												link
												@click="previewFile(url)"
												>预览</el-button
											>
										</template>
									</template>
									<template v-else-if="pageInfo.FieldDefines![field.FieldIndex!].InputDataType !==0">
										<el-link
											type="primary"
											v-if="pageInfo.FieldDefines![field.FieldIndex!]?.Extend?.fieldLinkConfig?.isOpen"
											@click="handleFieldJump(pageInfo.FieldDefines![field.FieldIndex!]?.Extend?.fieldLinkConfig, scope.row)"
											>{{ handleViewData(pageInfo.FieldDefines![field.FieldIndex!], scope.row) }}</el-link
										>
										<template v-else>
											<el-tag v-if="pageInfo.FieldDefines![field.FieldIndex!].InputType === 'el-select'">{{
												handleViewData(pageInfo.FieldDefines![field.FieldIndex!], scope.row)
											}}</el-tag>
											<span v-else>{{ handleViewData(pageInfo.FieldDefines![field.FieldIndex!], scope.row) }}</span>
										</template>
									</template>
									<template v-else>
										<el-link
											type="primary"
											v-if="pageInfo.FieldDefines![field.FieldIndex!]?.Extend?.fieldLinkConfig?.isOpen"
											@click="handleFieldJump(pageInfo.FieldDefines![field.FieldIndex!]?.Extend?.fieldLinkConfig, scope.row)"
										>
											{{ getViewData(pageInfo.FieldDefines![field.FieldIndex!], scope.row[field.FieldName]) }}</el-link
										>
										<template v-else>
											<el-tag v-if="pageInfo.FieldDefines![field.FieldIndex!].InputType === 'el-select'">{{
												getViewData(pageInfo.FieldDefines![field.FieldIndex!], scope.row[field.FieldName])
											}}</el-tag>
											<span v-else>{{ getViewData(pageInfo.FieldDefines![field.FieldIndex!], scope.row[field.FieldName]) }}</span>
										</template>
									</template>
								</template>
							</template>
						</el-table-column>
						<!-- 操作列渲染 -->
						<template v-else-if="'Col-' + field.Index && !props.isDisabledHanlde">
							<el-table-column
								:label="field.ColumnName"
								align="center"
								:width="field.ViewSeqID ? (field.ColWidth ? field.ColWidth : 'auto') : ''"
								:[handlePropsFixed(field.FixedCol!)]="field.FixedCol?.fixedType"
							>
								<!-- 操作栏 -->
								<template #default="scope">
									<template v-for="(btn, index) in findBtns(field as OperateColumnDefType)" :key="'btns' + index">
										<el-button
											v-if="handleShowBtn(btn, scope.row)"
											:type="transformBtnColor(btn.BtnStyleColor)"
											:[transformBtnType(btn.BtnStyleType)]="true"
											size="small"
											@click="handleBtnClick({ ...btn, type: 'Column', index }, scope.row)"
											>{{ btn.Title }}</el-button
										>
									</template>
								</template>
							</el-table-column>
						</template>
					</template>
				</el-table>
			</div>
			<div v-if="pageConfig.pageShow" class="page">
				<el-pagination
					background
					:hide-on-single-page="pageInfo.NeedPagination"
					:layout="pageConfig.layout"
					:total="pageConfig.total"
					v-model:current-page="pageConfig.currentPage"
					:page-sizes="pageConfig.sizes"
					:page-size="pageConfig.pagesize"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
			<!-- 弹窗 -->
			<LxDialog
				v-model="showDialog"
				:dialogConfig="dialogConfig"
				:inputData="props.inputData"
				@getTableData="getData"
				@exportExcel="exportExcel"
				@handleEmitEvent="handleRefreshPage"
				:pageData="pageData"
			/>

			<!-- 导入弹窗 -->
			<LxDialog v-model="importDialog" :dialogConfig="dialogConfig">
				<template #main>
					<ImportExcel :importDefine="importDefine" :pageDefines="pageInfo" ref="importExcelRef" />
				</template>
				<template #footer>
					<el-button @click="handleCancelImport">取消</el-button> <el-button type="primary" @click="handleSubmitImport">确定</el-button></template
				>
			</LxDialog>
		</template>
	</div>
</template>

<script lang="ts" setup name="tablePage">
import { onBeforeRouteLeave, useRouter, useRoute } from 'vue-router';
import { FormInstance, ElMessage } from 'element-plus';
import {
	TablePageType,
	TabFieldType,
	DialogType,
	ShowDefineType,
	EInputDataType,
	ButtonDefineType,
	EventExcuteType,
	OperateColumnDefType,
	DialogConfigType,
	EInputType,
} from '/@/components/Linxyun/custom/DataStructs/commontype';
import { httpReqeustApi } from '/@/api/linxyun/base';
// import { TabPageItem } from '../CustomCommon/tab_page_item.js';
import { getComponent } from '/@/utils/componentFactory';
import { compare, getArrayIndex } from '/@/utils/extendMethods';
import Lxy_page_event_remote from '../CustomCommon/lxy_page_event_remote.js';
import useTablePage from './hooks/useTablePage';
import useBtnOperate from './hooks/useBtnOperate';

import LxDialog from '../../element/lx-dialog.vue';
import ImportExcel from '../../ImportExcel/index.vue';
import type { IStateType } from './type';
import { calcFieldValue } from '/@/components/Linxyun/custom/CustomCommon/lxy_expression.js';

import { useCustomTableStore } from '/@/stores/customTable';

import { createDDE_SA } from '/@/utils/stringUtil';

export interface IPropsType {
	pageInfo?: TablePageType;
	inputData?: Record<string, any>;
	isDisabledHanlde?: boolean;
	isTabRadio?: boolean;
	fromPageID?: number;
}
const router = useRouter();
const route = useRoute();
const httpRequest = httpReqeustApi();
const customTableStore = useCustomTableStore();

const props = withDefaults(defineProps<IPropsType>(), {
	inputData: () => ({}),
	pageData: () => ({}),
	isDisabledHanlde: false,
	isTabRadio: false,
	fromPageID: -1,
});
const emit = defineEmits(['queryData', 'dialogCloseRefreshEmit']);

const state = reactive<IStateType>({
	componentSit: [],
	refInfo: {},
	tabPageItem: {},
	pageConfig: { sizes: [5, 10, 20, 30], layout: 'total, sizes, prev, pager, next, jumper', total: 0, pagesize: 10, pageShow: true, currentPage: 1 },
	pageData: {},
	queryParams: {},
	globalData: {},
	showDialog: false,
	dialogConfig: {
		title: '',
		fieldDefines: [],
		submitUrl: '',
		width: 'auto',
		opType: null,
	},
	FilterFields: [],
	importDialog: false,
	importDefine: {},
	rowIndex: -1,
	colIndex: -1,
	batchInterface: {
		add: '',
		update: '',
	},
});
const {
	componentSit,
	refInfo,
	tabPageItem,
	pageConfig,
	pageData,
	queryParams,
	globalData,
	dialogConfig,
	showDialog,
	FilterFields,
	importDialog,
	importDefine,
} = toRefs(state);
const searchFormRef = ref<FormInstance>();

const setting = localStorage.getItem('setting');
const prefixUrl = ref('');
if (setting) {
	prefixUrl.value = JSON.parse(setting).ImagUrl || '';
}
// 判断参数是否正确
if (!props.pageInfo) {
	console.log('props.pageInfo.ColButtonDefines', props.pageInfo);
}
console.log('[Debug][TablePage][Init], searchParamsList: ', props.pageInfo?.FilterDefines);
const { pageInfo, inputData } = toRefs(props);
const isDialogTablePage = inject('dialogTablePage', false);
// 初始化的时候获取当前页码
if (!isDialogTablePage) {
	pageConfig.value.currentPage = Number(localStorage.getItem('currentPage')) || 1;
}

const setRefInfo = (el: any, itemKey: string) => {
	refInfo.value[itemKey] = el;
};

interface btnDefineE extends ButtonDefineType {
	type?: string;
	index?: number;
}
const handleBtnClick = (btnDefine: btnDefineE, row?: Record<string, any>) => {
	console.log(btnDefine);
	if (!btnDefine.EventDefine) {
		console.error('TablePage handleBtnClick EventDefine:', btnDefine.EventDefine);
		return;
	}

	const { OpType, IsBatch, QueryRequiresBatchDataUrl, Params } = btnDefine.EventDefine.DialogDefine;
	if (row?.isTabTempData && ![DialogType.delete].includes(OpType) && btnDefine.type) {
		return ElMessage.warning('临时数据该按钮不可以操作');
	}
	if (!btnDefine.SubmitUrl && OpType !== DialogType.print && OpType !== DialogType.detail) {
		console.error('TablePage handleBtnClick SubmitUrl:', btnDefine.SubmitUrl);
		return;
	}

	//  OpType === DialogType
	// 按钮类型
	switch (OpType) {
		case DialogType.query: // 查询
			handleSearch();
			break;
		case DialogType.add: // 添加
			showDialog.value = true;
			if (!IsBatch) {
				dialogConfig.value.title = '新增';
				dialogConfig.value.submitUrl = btnDefine.SubmitUrl;
				dialogConfig.value.opType = OpType;
				dialogConfig.value.width = pageInfo!.value!.PopupSize || 'auto';
				dialogConfig.value.fieldDefines = filterFieldDefines(pageInfo!.value!.AddShowDefines!, DialogType.add) || [];
				state.dialogConfig.isDisabledHanlde = false;
			} else {
				state.dialogConfig.title = '批量';
				state.dialogConfig.opType = DialogType.customize;
				state.dialogConfig.ot = EventExcuteType.Customizepage;
				state.dialogConfig.submitUrl = QueryRequiresBatchDataUrl || ''; // pageid
				state.dialogConfig.width = pageInfo?.value?.PopupSize || 'auto';
				state.dialogConfig.superiorParams = {};
				state.dialogConfig.formData = {};
				state.dialogConfig.isDisabledHanlde = true;
				state.dialogConfig.paramsMap = Params || [];
				state.dialogConfig.batchAddUrl = btnDefine.SubmitUrl;
				state.dialogConfig.fromPageID = props.pageInfo?.PageId || -1;
			}
			console.log('dialogConfig', dialogConfig.value);
			break;
		case DialogType.edit: // 修改
			showDialog.value = true;
			dialogConfig.value.title = '修改';
			dialogConfig.value.submitUrl = btnDefine.SubmitUrl;
			dialogConfig.value.opType = OpType;
			dialogConfig.value.width = pageInfo!.value!.PopupSize || 'auto';
			dialogConfig.value.formParmas = row;
			dialogConfig.value.fieldDefines = filterFieldDefines(pageInfo!.value!.EditShowDefines!, DialogType.edit) || [];
			console.log('dialogConfig', dialogConfig.value);
			break;
		case DialogType.delete: // 删除
			handleDeleteRow(btnDefine, row!);
			break;
		case DialogType.customize: // 自定义
			console.log('自定义');
			handleCustomize({ ...btnDefine, PageID: pageInfo?.value?.PageId }, OpType, row, multipleSelection.value);
			break;
		case DialogType.detail: //详情
			showDialog.value = true;
			dialogConfig.value.title = '详情';
			dialogConfig.value.opType = OpType;
			dialogConfig.value.formParmas = row;
			dialogConfig.value.width = pageInfo!.value!.PopupSize || 'auto';
			dialogConfig.value.fieldDefines = pageInfo!.value!.FieldDefines! || [];

			dialogConfig.value.ExcuteData = btnDefine.EventDefine.DialogDefine.ExcuteData;

			break;
		case DialogType.export: // 导出
			const fieldDefines: TabFieldType[] = [];
			const temp: TabFieldType = {
				PageID: 9999,
				FieldID: '',
				FieldName: '',
				Label: '',
				InputType: 'el-input',
				Type: '0',
				IsViewInTab: true,
				ColWidth: 0,
				InputDataType: 0,
				InputDataCfg: '',
				IsFilter: true,
				FilterWidth: 0,
				TipsText: '',
				IsAddNeed: true,
				AddColWidth: 0,
				AddSeqID: 0,
				AddProcessType: 4,
				IsEditNeed: true,
				EditColWidth: 0,
				EditSeqID: 0,
				EditProcessType: 3,
				Accuracy: {
					open: '0',
					digit: 2,
				},
				IfCascadeShow: false,
				CascadeCfg: {
					type: '',
					label: '',
					value: '',
				},
				NeedVerify: false,
				VerifyFunc: '',
				Extend: '',
				DataStorageMode: 'file',
				InputDefine: null,
				Doptions: [],
				InputCheck: { isCheck: 0, type: 1, value: '', tips: '' },
			};
			fieldDefines.push({ ...temp, FieldName: 'FileName', Label: '文件名', TipsText: '请输入文件名' });
			fieldDefines.push({ ...temp, FieldName: 'SheetName', Label: '工作表名', TipsText: '请输入工作表名' });
			showDialog.value = true;
			dialogConfig.value.title = '导出';
			dialogConfig.value.submitUrl = btnDefine.SubmitUrl;
			dialogConfig.value.opType = OpType;
			dialogConfig.value.width = pageInfo!.value!.PopupSize || 'auto';
			dialogConfig.value.fieldDefines = fieldDefines;

			dialogConfig.value.params = {};
			const searchParams = pageInfo?.value?.SearchEvent.event.params;
			for (let index = 0; index < searchParams.length; index++) {
				const value = calcFieldValue(4, searchParams[index].value, props.inputData, state.pageData, state.globalData);
				dialogConfig.value.params[searchParams[index].name] = value;
			}

			break;
		case DialogType.import: // 导入
			const InPutData = btnDefine.EventDefine?.DialogDefine?.InPutData;
			if (!InPutData) return console.error('InPutData:', InPutData);
			dialogConfig.value.opType = OpType;
			dialogConfig.value.title = '导入';
			dialogConfig.value.width = 'auto';
			dialogConfig.value.fieldDefines = [];
			importDialog.value = true;
			importDefine.value = {
				label: btnDefine.EventDefine.DialogDefine.Title,
				startRow: InPutData.StartRow,
				interface: btnDefine.SubmitUrl,
				eventData: InPutData.ColData,
			};
			handleImportExCel();
			break;
		case DialogType.print: // 打印
			window.print();
			break;
		case DialogType.down: // 导出模板
			location.href = btnDefine.SubmitUrl;
			break;
	}
};

// 查找列按钮
const findBtns = computed(() => {
	return (OperateColumnDef: OperateColumnDefType) => {
		let btns: ButtonDefineType[] = [];
		// console.log('OperateColumnDef', OperateColumnDef, pageInfo?.value?.ColButtonDefines);
		const res = pageInfo?.value?.ColButtonDefines?.find((col) => {
			return 'Col-' + OperateColumnDef.Index === 'Col-' + col.Index;
		});
		if (res) {
			btns = res.btns;
		}

		return btns;
	};
});

const handlePropsFixed = (FixedCol: { fixedType: 'left' | 'right'; isFixed: boolean }) => {
	// console.log('handlePropsFixed', FixedCol);
	return FixedCol.isFixed ? 'fixed' : 'aaa';
};

// 导出excel
const exportExcel = (formData: Record<string, any>, params: Record<string, unknown>) => {
	const tableShowDefines: TabFieldType[] = filterFieldDefines(pageInfo!.value!.TableShowDefines!) || [];
	handleExportExcel(tableShowDefines, dialogConfig.value.submitUrl, formData, getViewData, params);
};
// 过滤 fieldDefines
const filterFieldDefines = (Fields: ShowDefineType[] | (ShowDefineType | OperateColumnDefType)[], type?: DialogType) => {
	if (Fields === undefined) {
		console.error('filterFieldDefines Fields:', Fields);
		return;
	} else if (Fields.length === 0) {
		console.error('filterFieldDefines Fields length:', Fields, 'length:', Fields.length);
	}
	if (type) {
		const fieldList = Fields.map((field: ShowDefineType) => {
			return pageInfo!.value!.FieldDefines![field.FieldIndex];
		});
		if (type === DialogType.add) {
			return fieldList.sort(compare('AddSeqID'));
		} else if (type === DialogType.edit) {
			return fieldList.sort(compare('EditSeqID'));
		}
	} else {
		const newFields = [];
		for (let index = 0; index < Fields.length; index++) {
			if (!Fields[index].FieldIndex && !Fields[index].FieldName) {
				continue;
			}
			newFields.push(pageInfo!.value!.FieldDefines![Fields[index].FieldIndex!]);
		}
		return newFields;
	}
};

const getFilterFields = () => {
	// debugger;
	// const FilterFields: TabFieldType[] = [];
	// console.log('getFilterFields', pageInfo!.value);
	if (pageInfo && pageInfo.value && pageInfo.value.FilterDefines) {
		for (let i = 0; i < pageInfo.value.FilterDefines.length; i++) {
			if (pageInfo.value.FieldDefines && pageInfo.value.FieldDefines.length > pageInfo.value.FilterDefines[i].FieldIndex) {
				const FilterField = pageInfo.value.FieldDefines[pageInfo.value.FilterDefines[i].FieldIndex];
				FilterFields.value.push(FilterField);
				queryParams.value[FilterField.FieldName] ||= '';
			} else {
				console.error('getFilterFields error, FilterFields: ', pageInfo.value.FilterDefines);
				console.error('getFilterFields error, FieldDefines: ', pageInfo.value.FieldDefines);
			}
		}
	}
	// console.log('FilterFields', FilterFields, pageInfo!.value);
	return FilterFields;
};

// =========== start 分页器的函数 ===========
// 每页条数改变时调用
const handleSizeChange = (size: number) => {
	console.log('handleCurrentChange size: ', size);
	pageData.value.limit = size;
	pageConfig.value.pagesize = size;
	console.log('handleCurrentChange pageData: ', pageData.value);
	getData();
};

// 当前页改变时调用
const handleCurrentChange = (current: number) => {
	console.log('handleCurrentChange current: ', current);
	// emits('queryData', null, pageData.value);
	pageData.value.current = current;
	if (!isDialogTablePage) {
		pageConfig.value.currentPage = current;
	}
	getData();

	// 保存当前页码 为了防止刷新页码回到第一页
	window.localStorage.setItem('currentPage', current + '');
};
// =========== end 分页器的函数 ===========

const getSummaries = (param: any) => {
	const { columns, data } = param;
	const sums: any[] = [];
	columns.forEach((column: any, index: number) => {
		if (index === 0) {
			sums[index] = '统计';
			return;
		}
		const values = data.map((item: any) => Number(item[column.property]));
		if (!values.every((value: any) => isNaN(value)) && pageInfo?.value?.StatisticsDefines!.find((fd) => fd === column.property)) {
			sums[index] = values.reduce((prev, curr) => {
				const value = Number(curr);
				if (!isNaN(value)) {
					return prev + curr;
				} else {
					return prev;
				}
			}, 0);
		}
	});

	// this.sums = sums
	console.log('getSummaries', param, sums);
	return sums;
};

const gethtml = () => {
	console.log(refInfo.value['lx_input1'].getHtml());
};
// 数据发生改变时调用 因为刚开数据为空
watch(
	() => pageInfo!.value!.SearchEvent,
	(val) => {
		// console.log('watch SearchEvent', val);
		getFilterFields();
		getData();
	}
);
// 请求数据
const getData = async () => {
	if (!pageInfo?.value?.SearchEvent?.event?.url) {
		console.error('[Error][queryData]No set search event url, can not query data, tab: ', pageInfo?.value);
		return;
	}

	state.rowIndex = -1;
	const filterParams: Record<string, any> = {};
	// 每页条数
	if (pageData.value.limit) {
		filterParams.limit = pageData.value.limit;
	} else {
		filterParams.limit = 10;
	}
	// 第几页
	if (pageData.value.current) {
		filterParams.current = pageData.value.current;
	} else if (pageConfig.value.currentPage && !isDialogTablePage) {
		console.log('getData currentPage', pageConfig.value.currentPage);
		filterParams.current = pageConfig.value.currentPage;
	} else {
		filterParams.current = 1;
	}

	// 携带上级传过来的参数
	FilterFields.value.forEach((item) => {
		if (item.InputDataType === EInputDataType.PassFromUp) {
			filterParams[item.FieldName] = props.inputData[item.InputDataCfg!];
		}
	});
	for (let i = 0; i < FilterFields.value.length; i++) {
		// console.log('search, searchParams', FilterFields.value, queryParams.value);
		if (
			queryParams.value.hasOwnProperty(FilterFields.value[i].FieldName) &&
			queryParams.value[FilterFields.value[i].FieldName] !== null &&
			queryParams.value[FilterFields.value[i].FieldName] !== ''
		) {
			console.log('00000: ', queryParams.value[FilterFields.value[i].FieldName]);
			if (FilterFields.value[i].InputType === 'el-cascader') {
				const arData: any[] = queryParams.value[FilterFields.value[i].FieldName] || [];
				if (!Array.isArray(arData)) {
					console.error('[Error]Filter data not array for cascader, key : ', FilterFields.value[i].FieldName);
					continue;
				}
				if (arData.length > 0) {
					filterParams[FilterFields.value[i].FieldName] = arData[arData.length - 1];
				}
			} else {
				filterParams[FilterFields.value[i].FieldName] = queryParams.value[FilterFields.value[i].FieldName];
			}
		}
		if (['el-time', 'el-date'].includes(FilterFields.value[i].InputType) && FilterFields.value[i].InputDefine?.filterType === 'range') {
			const val = queryParams.value[FilterFields.value[i].FieldName];
			// console.log('val', val);
			if (val) {
				filterParams[FilterFields.value[i].InputDefine.start || 'StartTime'] = val[0];
				filterParams[FilterFields.value[i].InputDefine.end || 'EndTime'] = val[1];
			} else {
				filterParams[FilterFields.value[i].InputDefine.start || 'StartTime'] = '';
				filterParams[FilterFields.value[i].InputDefine.end || 'EndTime'] = '';
			}
			console.log('filterParams', filterParams, FilterFields.value[i].FieldName);
			Reflect.deleteProperty(filterParams, FilterFields.value[i].FieldName);
		}
	}

	let urlParams = {};
	console.log('aased', route.query);
	if (route.query?.queryParams) {
		try {
			const queryParams = JSON.parse(route.query!.queryParams as string);
			urlParams = { ...queryParams };
		} catch (e) {
			console.log(e);
		}
	} else if (props.inputData.queryParams) {
		try {
			urlParams = { ...props.inputData.queryParams };
		} catch (e) {
			console.log(e);
		}
	}
	// console.log('pageInfo!.value!.SearchEvent.event', pageInfo!.value!.SearchEvent.event);
	const remoteEvent = new Lxy_page_event_remote(pageInfo!.value!.SearchEvent.event);
	console.log('[TablePage] getData inputData', props.inputData, queryParams.value, filterParams);
	remoteEvent.setDataSrc({ ...pageData.value, ...queryParams.value }, props.inputData);
	const result = await remoteEvent.callEvent({ ...filterParams, ...urlParams });

	const unshiftBatchAddData = () => {
		if (customTableStore.batchAddData.length && customTableStore.fromPageID === props.pageInfo?.PageId && customTableStore.fromPageID !== -1) {
			for (let index = 0; index < customTableStore.batchAddData.length; index++) {
				const item = customTableStore.batchAddData[index];
				for (let j = 0; j < (props.pageInfo.FieldDefines || []).length; j++) {
					const fieldDefine = props.pageInfo.FieldDefines![j];
					if (item[fieldDefine.FieldName] || fieldDefine.InputDataType === EInputDataType.FrontType) continue;
					const value = calcFieldValue(fieldDefine.InputDataType, fieldDefine.InputDataCfg, props.inputData, props.pageData);
					if (value) item[fieldDefine.FieldName] = value;
				}
			}
			pageData.value.tableData.unshift(...customTableStore.batchAddData);
		}
	};
	// console.log('getData res', result);
	if (!result) {
		console.error('[Error]query data fail, url: ', pageInfo!.value!.SearchEvent.event.url);
		return;
	}
	pageConfig.value.total = result.TotalSize ? result.TotalSize * 1 : 0;
	if (!result.Records) {
		pageData.value.tableData = [];
		unshiftBatchAddData();
		return;
	}
	for (let index = 0; index < result.Records.length; index++) {
		const item = result.Records[index];
		const fieldDefines = props.pageInfo?.FieldDefines || [];
		for (let index2 = 0; index2 < fieldDefines.length; index2++) {
			const fieldDefine = fieldDefines[index2];
			item[fieldDefine.FieldName] =
				fieldDefine.Accuracy.open === '1'
					? [undefined, null, NaN, ''].includes(item[fieldDefine.FieldName])
						? '0.00'
						: Number(item[fieldDefine.FieldName]).toFixed(fieldDefine.Accuracy.digit)
					: item[fieldDefine.FieldName];
		}
	}
	pageData.value.tableData = result.Records;

	unshiftBatchAddData();

	// console.log('getData', pageData.value.tabData, pageInfo!.value!);
};

// 关闭导出excel
const handleCancelImport = () => {
	importDialog.value = false;
};

// 提交导入Excel
const importExcelRef = ref<InstanceType<typeof ImportExcel>>();
const handleSubmitImport = () => {
	importExcelRef.value!.importData();
	handleSearch(); // 查询最新数据
	importDialog.value = false;
};
const { getViewData, formatUrl, transformBtnColor, transformBtnType, previewFile } = useTablePage();
const { handleDeleteRow, handleExportExcel, handleImportExCel, handleReset, handleSearch, handleCustomize, handleShowBtn } = useBtnOperate(
	getData,
	state,
	props
);

// 离开当前页面时触发
onBeforeRouteLeave(() => {
	console.log('离开');
	// 页面离开时把页码设为 1
	if (!isDialogTablePage) {
		localStorage.setItem('currentPage', '1');
	}
});

const handleViewData = (field: TabFieldType, row: Record<string, any>) => {
	function getAccuracyVal(value: string) {
		return field.Accuracy.open === '1' ? ([undefined, null, NaN, ''].includes(value) ? '0.00' : Number(value).toFixed(field.Accuracy.digit)) : value;
	}
	try {
		if (field.InputDataType && field.InputDataType !== 2) {
			const tempPageData = { ...pageData.value, ...row };
			const value = calcFieldValue(field.InputDataType, field.InputDataCfg, props.inputData, tempPageData);
			const fieldVal: string = row[field.FieldName];
			return ![undefined, NaN, null, ''].includes(value) ? getAccuracyVal(value) : field.DefaultValue || getAccuracyVal(fieldVal);
		} else if (field.InputDataType === 2) {
			return field.InputDataCfg;
		} else if (field.DefaultValue) {
			return field.DefaultValue;
		}
	} catch (e) {
		if (field.DefaultValue) {
			return field.DefaultValue;
		}
		console.error('handleViewData', e);
	}
};
const isShowSearchCard = computed(() => {
	if (
		pageInfo?.value?.FilterDefines?.length === 0 &&
		pageInfo?.value?.ButtonDefines?.length === 1 &&
		pageInfo?.value?.ButtonDefines[0].ShowLocal === 'query'
	)
		return false;
	else return true;
});
// 刷新页面
const handleRefreshPage = () => {
	console.log('handleRefreshPage 刷新页面');
	getData();
};
const tableRowIndex = ref(-1);
const tableRowClassName = ({ row, rowIndex }: { row: Record<string, any>; rowIndex: number }) => {
	// 把每一行的索引放到row里
	row.index = rowIndex;
	if (!props.isTabRadio) return '';
	if (rowIndex === tableRowIndex.value) return 'highlight-row';
	return '';
};
const tableCellClassName = ({ column, columnIndex }) => {
	// 把每一列的索引放到column里
	column.index = columnIndex;
	return '';
};
const handleCellDbClick = (row, column, cell, event) => {
	// console.log('handleCellDbClick row', row.index);
	// console.log('handleCellDbClick column', column.index);
	state.rowIndex = row.index;
	state.colIndex = column.index;
	// console.log('handleCellDbClick', row, column, cell, event);
};
const multipleSelection = ref<Record<string, any>[]>([]);
const handleSelectTableChange = (val: Record<string, any>[]) => {
	multipleSelection.value = val;
	console.log('handleSelectTableChange', val);
};

const handleFieldJump = (fieldLinkConfig: Record<string, any> | undefined, row: Record<string, any>) => {
	console.log('handleFieldJump:', fieldLinkConfig, row);
	const queryParams = {};
	if (Array.isArray(fieldLinkConfig?.params)) {
		for (let index = 0; index < fieldLinkConfig!.params.length; index++) {
			const field = fieldLinkConfig?.params[index];
			const value = calcFieldValue(4, field.value, props.inputData, { ...(row || {}) });
			queryParams[field.name] = value;
		}
	}
	if (fieldLinkConfig?.type === 'jump') {
		const routers = router.getRoutes();
		console.log('routers', routers);
		const route = routers.find((item) => {
			return item.path.includes('/PageID=' + fieldLinkConfig.linkUrl);
		});
		if (route) {
			let params = {};
			if (fieldLinkConfig?.linkType) {
				params = {
					...queryParams,
				};
			} else {
				params = {
					queryParams: JSON.stringify(queryParams),
				};
			}
			router.push({
				path: route.path,
				query: params,
			});
		} else {
			ElMessage.error('该跳转链接不存在');
		}
	} else {
		state.dialogConfig.title = fieldLinkConfig?.linkName || '';
		state.dialogConfig.opType = DialogType.customize;
		state.dialogConfig.ot = fieldLinkConfig?.linkType ? EventExcuteType.TablePage : EventExcuteType.Customizepage;
		state.dialogConfig.submitUrl = fieldLinkConfig?.linkUrl; // pageid
		state.dialogConfig.width = props.pageInfo?.PopupSize || 'auto';

		state.dialogConfig.superiorParams = { queryParams };
		state.dialogConfig.formData = {};
		state.showDialog = true;
	}
};
const tempdialogConfig: Record<string, any> = inject('dialogConfig', {});
const handleBatchGoParentTable = async () => {
	console.log('handleBatchGoParentTable', tempdialogConfig);
	if (multipleSelection.value.length === 0) {
		return ElMessage.warning('请至少选择一条记录');
	}
	const addBtnConfig = props.pageInfo?.ButtonDefines?.find((btn) => btn.EventDefine?.DialogDefine.OpType === DialogType.add);
	if (!addBtnConfig) return;
	const proAll = [];
	for (let index = 0; index < multipleSelection.value.length; index++) {
		const item = { ...multipleSelection.value[index], isTabTempData: true };
		for (let j = 0; j < tempdialogConfig.paramsMap?.length || 0; j++) {
			const p = tempdialogConfig.paramsMap[j];
			if (item[p.value] && p.name !== p.value) {
				item[p.name] = item[p.value];
				Reflect.deleteProperty(item, p.value);
			}
		}
		proAll.push(item);
		customTableStore.fromPageID = props.fromPageID;
		customTableStore.setBatchAddData(proAll);
		emit('dialogCloseRefreshEmit');
	}
	console.log('handleBatchGoParentTable proAll', proAll);
};

const handleCurrentTabItem = (item: Record<string, any>) => {
	console.log('handleCurrentTabItem', item);
	customTableStore.setTableRowData(item);
	const index = getArrayIndex(state.pageData.tableData, item);
	tableRowIndex.value = index;
};

const handleBatchOperation = async () => {
	if (multipleSelection.value.length === 0) return ElMessage.warning('至少勾选一条数据');
	getBatchInterface();
	if (!props.pageInfo?.TableName) return;
	const DDE_SA = createDDE_SA(props.pageInfo.EntCode, 0, 0);
	const headers = { 'DDE-SA': DDE_SA, 'Content-Type': 'application/json;charset=UTF-8' };
	const res: Record<string, any> = await httpRequest.Post(
		'/eslithe/getProjectTableDefineNew.action',
		{},
		{ TableName: props.pageInfo?.TableName },
		headers
	);
	console.log('handleBatchOperation', res);
	// return;
	if (!res.success) return ElMessage.error('查询主键字段失败');

	const addUrl = state.batchInterface.add;
	const updateUrl = state.batchInterface.update;

	if (!addUrl || !updateUrl) return ElMessage.error('添加或修改接口未配置');
	const proAll = [];
	const PrimaryKeyArr = res.PrimaryKey.split('|');
	for (let index = 0; index < multipleSelection.value.length; index++) {
		const item = multipleSelection.value[index];

		let flag = true; // true是add
		for (let index = 0; index < PrimaryKeyArr.length; index++) {
			const PrimaryKey = PrimaryKeyArr[index];
			const fieldDefine = res.Records.find((item: Record<string, any>) => {
				return item.FieldName === PrimaryKey;
			});
			if (fieldDefine?.IsAutoIncrement === '1' && item[PrimaryKey]) {
				flag = false;
			}
		}

		proAll.push(
			new Promise((resolve, reject) => {
				httpRequest
					.Post(flag ? addUrl : updateUrl, {}, item)
					.then((res: any) => {
						resolve(res);
					})
					.catch((err) => {
						reject(err);
					});
			})
		);
	}

	try {
		const results = await Promise.allSettled(proAll);
		console.log('results', results);
		const errData = [];
		for (let index = 0; index < results.length; index++) {
			const res: Record<string, any> = results[index];
			if (res.status === 'rejected') {
				errData.push(res);
			}
		}
		if (errData.length) {
			ElMessage.warning('部分数据操作失败');
			console.error('批量操作失败的日志', errData);
		}
		customTableStore.setBatchAddData([]);
		console.log('handleBatchGoParentTable', multipleSelection.value);
		getData();
	} catch (e) {
		console.log('handleBatchGoParentTable err', e);
	}
};

// 获取批量操作的接口
const getBatchInterface = () => {
	if (state.batchInterface.add) return;
	const ButtonDefine = props.pageInfo?.ButtonDefines?.find((item: ButtonDefineType) => {
		return item.EventDefine?.DialogDefine.OpType === DialogType.add;
	});

	state.batchInterface.add = ButtonDefine?.SubmitUrl || '';
	state.batchInterface.update = ButtonDefine?.EventDefine?.DialogDefine?.UpdateUrl || '';
	console.log('getBatchInterface batchInterface', props.pageInfo?.PageId, state.batchInterface);
};

const getTabFieldValue = computed(() => {
	return (row: Record<string, any>, FieldDefine: TabFieldType) => {
		if (!row[FieldDefine.FieldName]) {
			return FieldDefine.DefaultValue;
		}
		return row[FieldDefine.FieldName] || '';
	};
});
</script>
<style scoped>
.page {
	margin-top: 10px;
}

.el-form.el-form--inline .el-form-item--large.el-form-item:last-of-type {
	margin-bottom: 0px !important;
}

.flexRow {
	/* margin-top: 20px; */
}
.table-box {
	/* max-height: calc(100vh - 290px); */
	overflow: auto;
}
.table-box :deep(.el-button--large) {
	/* padding: 0; */
}

.ipt-wrapper :deep(.el-form--inline .el-form-item) {
	margin-bottom: 0;
}
.iptCol.iptCol.iptCol {
	margin-bottom: 20px;
}
.ipt-wrapper :deep(.el-card__body) {
	padding: 20px 20px 0 20px;
}
.btn {
	margin-right: 20px;
}
.el-divider--horizontal {
	margin: 15px 0;
}

.table-box :deep(tr.highlight-row td) {
	background-color: #c5c5c5;
	/* color: var(--next-color-white); */
}
</style>
